<template>
  <div>
    <RePage>
      <div class="split-pane">
        <splitpane :splitSet="settingLR">
          <template #paneL>
            <div class="pr-[16px] h-full">
              <treeList ref="treeListRef" :treeProops="treeProops" :treeEvents="treeEvents" :pageShow="false"
                :inputShow="true">
                <template #input>
                  <div
                    class="p-[16px] h-[48px] border-b border-solid border-[var(--el-border-color-lighter)] bg-[var(--bg-2)] relative">
                    <div class="flex justify-between">
                      <div class="flex items-center gap-[8px] h-[16px]">
                        <!-- <el-icon class="w-[16px] h-[16px]">
                                <Grid />
                            </el-icon> -->
                        <titleList class="w-[16px] h-[16px] fill-[var(--text-color)]" />
                        <el-text class="font-bold !text-[16px] leading-[16px]">模板分组</el-text>
                      </div>
                      <div class="h-[16px]">
                        <el-icon class="w-[16px] h-[16px] cursor-pointer" @click="addGroups()"
                          v-auth="'system.publicGraph.createTplGroup'">
                          <CirclePlusFilled />
                        </el-icon>
                      </div>
                    </div>
                  </div>
                </template>
                <template #tree="{ node }">
                  <div class="w-full flex-bc">
                    <div>{{ node.label }}</div>
                    <div class="mr-[10px] flex-c" @click.stop>
                      <el-dropdown trigger="click"
                        v-if="haveRole('system.publicGraph.updateTplGroup') || haveRole('system.publicGraph.removeTplGroup')">
                        <el-icon>
                          <MoreFilled />
                        </el-icon>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item v-if="haveRole('system.publicGraph.updateTplGroup')"
                              @click="addGroups('编辑分组', 'edit', node.data)">编辑</el-dropdown-item>
                            <el-dropdown-item v-if="haveRole('system.publicGraph.removeTplGroup')"
                              @click="deleteGroups(node.data)">删除</el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                  </div>
                </template>
              </treeList>
            </div>
          </template>
          <template #paneR>
            <div class="pl-[20px]">
              <MyFormCreate :clear-event="getTableList" v-model="searchFrom" :rule="searchFormRules" :key="key">
                <el-button type="primary" @click="DebounceGetTableList">搜索</el-button>
                <sj-button custom-type="sinfo" @click="DebounceResetting">重置</sj-button>
              </MyFormCreate>
              <div class="mb-5" v-auth="'system.publicGraph.createGraphtpl'">
                <el-button type="primary" :icon="Plus" @click="add">添加</el-button>
              </div>
              <pure-table :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)" showOverflowTooltip
                border @selection-change="selectionChange" :isShowPag="false">
                <template #action="{ row }">
                  <el-space>
                    <sj-link custom-type="sblue" :underline="false" v-auth="'system.publicGraph.updatetpl'"
                      @click="draw(row)">设计</sj-link>
                    <sj-link custom-type="sblue" :underline="false" @click="preview(row)">预览</sj-link>
                    <sj-link custom-type="sblue" :underline="false" v-auth="'system.publicGraph.updatetpl'"
                      @click="edit(row)">编辑</sj-link>
                    <sj-link custom-type="sred" :underline="false" v-auth="'system.publicGraph.removetpl'"
                      @click="deletes(row)">删除</sj-link>
                  </el-space>
                </template>
              </pure-table>
              <div class="mt-5">
                <el-pagination v-model:current-page="searchFrom.page" v-model:page-size="searchFrom.limit" background
                  :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList"
                  @current-change="getTableList" />
              </div>
            </div>
          </template>
        </splitpane>
      </div>
    </RePage>
  </div>
</template>
<script lang="ts" setup>
import { haveRole, initPureTableConfig } from '@/utils/functions'
import titleList from '@/assets/images/svg/title_list.svg'
import treeList from '@/components/treeList/treeList.vue'
import MyFormCreate from "@/components/MyFormCreate/index.vue";
import RePage from "@/components/RePage/index.vue";
import editForm from "./form.vue";
import { reactive, ref, h } from 'vue';
import { PAGE_LAYOUT } from '@/constant';
import { Plus, MoreFilled, CirclePlusFilled } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from "element-plus";
import { getList, getInfo, addInfo, editInfo, deleteInfo, getGroupList, addGroup, editGroup, deleteGroup } from '@/api/manage/topo-management/public/index';
import { titles, defaultSearchForm, prompt, defaultInfoForm } from './index';
import { addDialog } from "@/components/ReDialog";
import { deviceDetection, debounce, cloneDeep } from "@pureadmin/utils";
import { message } from "@/utils/message";
import { customPromiseDebounce } from "@/utils/functions";
import splitpane, { ContextProps } from "@/components/ReSplitPane";
import folderForm from './folderForm.vue'


const searchFrom = ref(defaultSearchForm());
const key = ref(0);
const showInfo = ref();
const formRef = ref();
const treeListRef = ref();
const tableData = reactive({
  data: [],
  total: 0,
});

const searchFormRules = [
  {
    type: 'input', field: 'topoName', title: titles.topoName, value: null, props: {
      placeholder: prompt.topoName, clearable: true
    }
  },
  { type: 'number', field: 'page', title: 'page', hidden: true },
  { type: 'number', field: 'limit', title: 'limit', hidden: true },
];
const selectionData = ref([]);
const roleTableConfig = [
  { prop: 'id', width: 100, label: titles.id, fixed: 'left' },
  { prop: 'topoName', label: titles.topoName },
  // { prop: 'updatedBy', label: titles.updatedBy },
  // { prop: 'updatedByName', label: titles.updatedByName },
  { prop: 'updatedAt', label: titles.updatedAt },
  { prop: 'remark', label: titles.remark },
  // { prop: 'unityName', label: titles.unityName },
  { slot: 'action', label: titles.action, width: 170, fixed: 'right' },
];
const checkedGroupId = ref(null)
const treeDataList = ref([]);
const props = {
  label: "groupName",
  value: "id"
};
const settingLR: ContextProps = reactive({
  minPercent: 17,
  maxPercent: 17,
  defaultPercent: 17,
  split: "vertical"
});
onMounted(() => {
  initDatas()
});
const initDatas = () => {
  getGroupList().then(res => {
    treeDataList.value = res.result.data
    treeListRef.value.getTreeRef().setCurrentKey(treeDataList.value[0].id);
    checkedGroupId.value = treeDataList.value[0].id
    getTableList()
  })
}

const getTreeList = () => {
  getGroupList().then(res => {
    treeDataList.value = res.result.data
  })
}
// 获取列表数据
const getTableList = () => {
  getList({ ...searchFrom.value, groupId: checkedGroupId.value }).then(res => {
    if (res.code === 200) {
      tableData.data = res.result.data;
      tableData.total = res.result.total;
    }
  })
}
// 重置搜索栏
const resetting = () => {//点击重置按键
  Object.assign(searchFrom.value, defaultSearchForm())
  key.value++
  getTableList()
}
// 新增
const add = () => {
  showInfo.value = {}
  openDialog()
}
// 编辑
const edit = (row) => {
  showInfo.value = {}
  openDialog("编辑", row)
}
// 删除
const deletes = (row?) => {
  ElMessageBox.confirm(
    `确认删除${row ? '当前' : '选中的'}数据?`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      deleteInfo({ ids: row ? [row.id] : selectionData.value.map(item => item.id) }).then(res => {
        if (res.code == 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getTableList();
        }
      })
    })
}
const addGroups = (title = '新增分组', type = 'add', editRow?) => {
  addDialog({
    title: title,
    width: "400px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    props: {
      formInline: {}
    },
    contentRenderer: () => h(folderForm, { ref: formRef }),
    openAutoFocus({ options, index }) {
      if (type == 'edit') {
        options.props.formInline = cloneDeep(editRow)
      } else {
        options.props.formInline = {
          groupName: '',
        }
      }

    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const formData = options.props.formInline;
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        getTreeList()
        done();
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          options.props.isLoading = true;
          if (type == 'add') {
            DebounceAddFolder(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          } else {
            DebounceEditFolder(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          }

        }
      });
    }
  });
}
const deleteGroups = (row) => {
  ElMessageBox.confirm('此操作将永久删除该分组, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteGroup({
      id: row.id
    }).then(res => {
      message('删除成功', { type: 'success' })
      if (row.id == checkedGroupId.value) {
        initDatas()
      } else {
        getTreeList()
      }
    })
  }).catch(() => {
    message('已取消删除', { type: 'info' })
  })
}
// 开启弹窗
const openDialog = (title = "新增", row?: any) => {
  addDialog({
    title: `${title}`,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(editForm, { ref: formRef }),
    open({ options }) {
      if (row) {
        showInfo.value = row
        options.props = {
          isLoading: false,
          formInline: cloneDeep(row)
        }
      } else {
        options.props = {
          isLoading: false,
          formInline: defaultInfoForm()
        }
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const formData = options.props.formInline;
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        getTableList(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          // console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;
          if (title === "新增") {
            formData.groupId = checkedGroupId.value
            DebounceAddInfo(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          } else {
            DebounceEditInfo(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          }
        }
      });
    }
  });
}
// 绘制
const draw = (row) => {
  window.open(
    window.location.protocol + "//" + window.location.host + "/#/configuration-page/configuration-page?id=" + row.id + '&unityId=' + row.unityId + '&type=1&source=manage',
    "_blank"
  );
}
const preview = (row) => {
  window.open(
    window.location.protocol + "//" + window.location.host + "/#/configuration-page/configuration-page/views?id=" + row.id + '&projectId=' + row.projectId + '&type=2&source=manage',
    "_blank"
  );
}
const selectionChange = data => {
  selectionData.value = data;
};
const handleNodeClick = data => {
  checkedGroupId.value = data.id
  getTableList()
};

const treeProops = ref({
  props: props,
  data: treeDataList,
  nodeKey: "value",
  'item-size': 46,
  'highlight-current': true
});
const treeEvents = {
  nodeClick: handleNodeClick,
};
// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
// 添加请求
const DebounceAddInfo = customPromiseDebounce(addInfo, 1000, true);
// 编辑请求
const DebounceEditInfo = customPromiseDebounce(editInfo, 1000, true);

const DebounceAddFolder = customPromiseDebounce(addGroup, 1000, true);
const DebounceEditFolder = customPromiseDebounce(editGroup, 1000, true);
</script>
<style lang="scss" scoped>
.split-pane {
  width: 100%;
  height: calc(100vh - 200px);
}
</style>
